package com.wyix;

import com.wyix.dao.OrderDAO;
import com.wyix.dao.ProductDAO;
import com.wyix.dao.UserDAO;
import com.wyix.domain.Order;
import com.wyix.domain.Product;
import com.wyix.domain.User;
import com.wyix.util.DBUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author wangdx
 * @since 2025/8/22
 */
public class JDBCDemo {
    private static UserDAO userDAO = new UserDAO();
    private static ProductDAO productDAO = new ProductDAO();
    private static OrderDAO orderDAO = new OrderDAO();
    private static Scanner scanner = new Scanner(System.in);
    private static User currentUser = null;

    public static void main(String[] args) {
        System.out.println("=== 欢迎使用JDBC电子商务系统 ===");

        // 初始化一些测试数据
        initTestData();

        // 显示主菜单
        showMainMenu();
    }

    /**
     * 初始化测试数据
     */
    private static void initTestData() {
        // 添加一些测试商品（使用批量添加）
        List<Product> products = new ArrayList<>();
        products.add(new Product("Java编程思想", "经典Java编程书籍", 108.0, 100));
        products.add(new Product("MySQL从入门到精通", "数据库学习指南", 89.0, 80));
        products.add(new Product("Spring实战", "Spring框架学习", 99.0, 60));
        products.add(new Product("JavaScript高级程序设计", "前端开发经典", 129.0, 50));

        int added = productDAO.batchAddProducts(products);
        System.out.println("初始化测试商品：" + added + "件商品添加成功");

        // 添加一个测试用户
        User testuser = userDAO.findByUsername("testuser");
        if (testuser == null) {
            User testUser = new User("testuser", "123456", "test@example.com");
            if (userDAO.register(testUser)) {
                System.out.println("初始化测试用户：testuser，密码：123456");
            }
        }
    }

    /**
     * 显示主菜单
     */
    private static void showMainMenu() {
        while (true) {
            System.out.println("\n=== 主菜单 ===");
            if (currentUser == null) {
                System.out.println("1. 用户注册");
                System.out.println("2. 用户登录");
                System.out.println("3. 浏览商品");
                System.out.println("0. 退出系统");
            } else {
                System.out.println("当前用户：" + currentUser.getUsername() + "，余额：" + currentUser.getBalance());
                System.out.println("1. 充值余额");
                System.out.println("2. 浏览商品");
                System.out.println("3. 购买商品");
                System.out.println("4. 我的订单");
                System.out.println("5. 退出登录");
                System.out.println("0. 退出系统");
            }

            Scanner scanner = new Scanner(System.in);
            int choice = 0;
            boolean validInput = false;

            while (!validInput) {
                try {
                    System.out.print("请选择操作：");
                    choice = scanner.nextInt();
                    validInput = true;
                } catch (Exception e) {
                    System.out.println("输入无效，请输入数字！");
                    scanner.nextLine();
                }
            }
            switch (choice) {
                case 1:
                    if (currentUser == null) {
                        register();
                    } else {
                        recharge();
                    }
                    break;
                case 2:
                    if (currentUser == null) {
                        login();
                    } else {
                        browseProducts();
                    }
                    break;
                case 3:
                    if (currentUser == null) {
                        browseProducts();
                    } else {
                        purchaseProduct();
                    }
                    break;
                case 4:
                    if (currentUser != null) {
                        viewMyOrders();
                    } else {
                        System.out.println("请先登录");
                    }
                    break;
                case 5:
                    if (currentUser != null) {
                        currentUser = null;
                        System.out.println("已退出登录");
                    } else {
                        System.out.println("无效操作");
                    }
                    break;
                case 0:
                    System.out.println("谢谢使用，再见！");
                    scanner.close();
                    System.exit(0);
                    break;
                default:
                    System.out.println("无效的选择，请重新输入");
            }
        }
    }

    /**
     * 用户注册
     */
    private static void register() {
        System.out.println("\n=== 用户注册 ===");
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();
        System.out.print("请输入邮箱：");
        String email = scanner.nextLine();

        User user = new User(username, password, email);
        if (userDAO.register(user)) {
            System.out.println("注册成功！");
        } else {
            System.out.println("注册失败！");
        }
    }

    /**
     * 用户登录
     */
    private static void login() {
        System.out.println("\n=== 用户登录 ===");
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        User user = userDAO.login(username, password);
        if (user != null) {
            currentUser = user;
            System.out.println("登录成功！欢迎回来，" + username + "！");
        } else {
            System.out.println("用户名或密码错误，登录失败！");
        }
    }

    /**
     * 充值余额
     */
    private static void recharge() {
        System.out.println("\n=== 充值余额 ===");
        System.out.print("请输入充值金额：");
        double amount = scanner.nextDouble();
        scanner.nextLine(); // 消费换行符

        if (amount <= 0) {
            System.out.println("充值金额必须大于0");
            return;
        }

        try {
            // 使用事务更新余额
            java.sql.Connection conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            boolean success = userDAO.updateBalance(conn, currentUser.getId(), amount);
            if (success) {
                conn.commit();
                currentUser.setBalance(currentUser.getBalance() + amount);
                System.out.println("充值成功！当前余额：" + currentUser.getBalance());
            } else {
                conn.rollback();
                System.out.println("充值失败！");
            }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("充值失败！");
        }
    }

    /**
     * 浏览商品
     */
    private static void browseProducts() {
        System.out.println("\n=== 商品列表 ===");
        System.out.print("请输入搜索关键词（回车查看全部）：");
        String keyword = scanner.nextLine();

        List<Product> products = productDAO.searchProducts(keyword);

        if (products.isEmpty()) {
            System.out.println("没有找到符合条件的商品");
            return;
        }

        System.out.println("ID\t名称\t价格\t库存");
        for (Product product : products) {
            System.out.println(product.getId() + "\t" + product.getName() + "\t" +
                    product.getPrice() + "\t" + product.getStock());
        }
    }

    /**
     * 购买商品
     */
    private static void purchaseProduct() {
        System.out.println("\n=== 购买商品 ===");
        System.out.print("请输入要购买的商品ID：");
        int productId = scanner.nextInt();
        System.out.print("请输入购买数量：");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("购买数量必须大于0");
            return;
        }

        // 调用订单DAO创建订单（包含完整事务）
        Order order = orderDAO.createOrder(currentUser.getId(), productId, quantity);

        if (order != null) {
            System.out.println("购买成功！订单信息：");
            System.out.println("订单号：" + order.getOrderNo());
            System.out.println("商品ID：" + order.getProductId());
            System.out.println("数量：" + order.getQuantity());
            System.out.println("总金额：" + order.getTotalAmount());

            // 更新当前用户余额显示
            currentUser = userDAO.findById(currentUser.getId());
        } else {
            System.out.println("购买失败，请稍后重试");
        }
    }

    /**
     * 查看我的订单
     */
    private static void viewMyOrders() {
        System.out.println("\n=== 我的订单 ===");
        // 这里简化处理，实际应该查询当前用户的所有订单
        System.out.println("功能开发中，敬请期待...");
    }
}
